package com.zgx.plus.system.controller.system;

import cn.hutool.core.convert.Convert;
import com.zgx.plus.common.aop.Log;
import com.zgx.plus.common.base.BaseController;
import com.zgx.plus.common.enums.BusinessType;
import com.zgx.plus.common.exception.BizException;
import com.zgx.plus.common.response.R;
import com.zgx.plus.common.response.page.TableDataInfo;
import com.zgx.plus.security.model.LoginUser;
import com.zgx.plus.security.service.SysPermissionService;
import com.zgx.plus.security.service.TokenService;
import com.zgx.plus.system.api.dto.SysDeptDto;
import com.zgx.plus.system.api.dto.SysRoleDto;
import com.zgx.plus.system.api.pos.SysRole;
import com.zgx.plus.system.api.vos.SysRoleVo;
import com.zgx.plus.system.api.vos.SysUserRoleVo;
import com.zgx.plus.system.service.SysDeptService;
import com.zgx.plus.system.service.SysRoleService;
import com.zgx.plus.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysPermissionService permissionService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysRoleDto role) {
        startPage();
        return getDataTable(roleService.selectRoleList(role));
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) {
//  List<SysRole> list = roleService.selectRoleList(role);
//  ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
//  util.exportExcel(response, list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public R<SysRoleVo> getInfo(@PathVariable Long roleId) {
        try {
            return R.ok(roleService.selectRoleById(roleId));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("获取角色ID为{0}失败：{1}", roleId, e.getMessage()));
        }
    }

    /**
     * 新增角色
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysRoleVo role) {
        try {
            role.setCreateBy(getUsername());
            return R.ok(roleService.insertRole(role));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("新增角色为{0}失败：{1}", role.getRoleName(), e.getMessage()));
        }
    }

    /**
     * 修改保存角色
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysRoleVo role) {
        try {
            role.setUpdateBy(getUsername());
            if (roleService.updateRole(role)) {
                // 更新缓存用户权限
                LoginUser loginUser = Convert.convert(LoginUser.class, getLoginUser());
                if (Objects.nonNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                    loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                    loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                    tokenService.setLoginUser(loginUser);
                }
                return R.ok();
            }
            return R.fail(MessageFormat.format("修改角色{0}失败，请联系管理员", role.getRoleName()));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("修改角色{0}失败:{1}", role.getRoleName(), e.getMessage()));
        }
    }

    /**
     * 修改保存数据权限
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public R dataScope(@RequestBody SysRoleVo role) {
        try {
            return R.ok(roleService.authDataScope(role));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("修改角色{0}失败:{1}", role.getRoleName(), e.getMessage()));
        }
    }

    /**
     * 状态修改
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysRoleVo role) {
        try {
            role.setUpdateBy(getUsername());
            return R.ok(roleService.updateRoleStatus(role));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("修改角色{0}失败:{1}", role.getRoleName(), e.getMessage()));
        }
    }

    /**
     * 删除角色
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds) {
        try {
            return R.ok(roleService.deleteRoleByIds(roleIds));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("删除角色失败:{0}", e.getMessage()));
        }
    }

    /**
     * 获取角色选择框列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public R<List<SysRoleVo>> optionselect() {
        return R.ok(roleService.selectRoleAll());
    }

// /**
//  * 查询已分配用户角色列表
//  */
// @PreAuthorize("@ss.hasPermi('system:role:list')")
// @GetMapping("/authUser/allocatedList")
// public TableDataInfo allocatedList(SysUser user) {
//  startPage();
//  List<SysUser> list = userService.selectAllocatedList(user);
//  return getDataTable(list);
// }
//
// /**
//  * 查询未分配用户角色列表
//  */
// @PreAuthorize("@ss.hasPermi('system:role:list')")
// @GetMapping("/authUser/unallocatedList")
// public TableDataInfo unallocatedList(SysUser user) {
//  startPage();
//  List<SysUser> list = userService.selectUnallocatedList(user);
//  return getDataTable(list);
// }

    /**
     * 取消授权用户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public R cancelAuthUser(@RequestBody SysUserRoleVo userRole) {
        try {
            return R.ok(roleService.deleteAuthUser(userRole));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("取消授权用户失败:{0}", e.getMessage()));
        }
    }

    /**
     * 批量取消授权用户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public R cancelAuthUserAll(Long roleId, Long[] userIds) {
        try {
            return R.ok(roleService.deleteAuthUsers(roleId, userIds));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("批量取消授权用户失败:{0}", e.getMessage()));
        }
    }

    /**
     * 批量选择用户授权
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public R selectAuthUserAll(Long roleId, Long[] userIds) {
        try {
            return R.ok(roleService.insertAuthUsers(roleId, userIds));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("批量选择用户授权失败:{0}", e.getMessage()));
        }
    }


    /**
     * 获取对应角色部门树列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public R<Map<String, Object>> deptTree(@PathVariable("roleId") Long roleId) {
        try {
            Map<String, Object> ajax = new HashMap<>();
            ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
            ajax.put("depts", deptService.selectDeptTreeList(SysDeptDto.builder().build()));
            return R.ok(ajax);
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("获取对应角色部门树列表失败：{0}", e.getMessage()));
        }
    }
}
